<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use App\Models\Linkslistsminapps;
use App\Models\Linkslists;
use App\Models\Settingminiappsnotice;
use App\Models\Miniappsban;
use App\Models\Users;
use App\Models\Usersinfo;
use App\Jobs\Miniappupdate;
use App\Services\EmailService;
use App\Services\MiniappService;
use App\Services\CacheService;
use App\Services\WechattmplmsgService;
use Log,Exception,DB;

class Miniappdisable implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $appid;
    protected $visit_status;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($appid,$visit_status)
    {
        $this->appid = $appid;
        $this->visit_status = $visit_status;
    }
    /**
     * 在超时之前任务可以运行的秒数
     *
     * @var int
     */
    public $timeout = 1200;
    /**
     * 监听小程序是否被禁用
     *
     * @return void
     */
    public function handle()
    {
        try {            
            $appid = $this->appid;
            $linkListMiniapp = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
            if (empty($linkListMiniapp)) return "小程序不存在";
            if ($linkListMiniapp->disable == 2 || $linkListMiniapp->disable == 5) return "已删除";
            $miniappDisable = Redis::get("miniapp_change_".$appid);
            if (!empty($miniappDisable)) return "切换中,暂不处理!";
            $users_id = $linkListMiniapp->users_id;
            $visitName = ($this->visit_status == 2) ? "暂停服务" : "封禁";
            $appidNameNew = "";
            $appidNew = "";
            // 更新小程序为被下架
            Linkslistsminapps::updateLinksListMiniappDisable($appid,5,$this->visit_status);
            // 公用小程序
            if ($linkListMiniapp->status == 2) {
                // 只更新二维码专用,客服专用,点击版专用
                if (in_array($linkListMiniapp->type, [3,4,5])) {
                    if(in_array($linkListMiniapp->miniapp_type,[1,4]) && Redis::get("today_mini_times_".date('Ymd')) > 3){
                        $platfromUseable = Linkslistsminapps::getPublicUseableMinappsBySecret();
                    }else{
                        $platfromUseable = Linkslistsminapps::getPublicUseableMinappsByscan();
                    } 
                    if(empty($platfromUseable)) $platfromUseable = Linkslistsminapps::getPublicUseableMinapps();
                    // 免费小程序被封
                    if (empty($platfromUseable)) {
                        $message = "二维码小程序".$visitName."无备用";
                    } else {
                        if(in_array($linkListMiniapp->miniapp_type,[1,4])){
                            Redis::incr("today_mini_times_".date('Ymd'));
                        }
                        Redis::setex("miniapp_change_".$platfromUseable->appid,600,"1");
                        // 把小程序设为默认
                        Linkslistsminapps::updatePublicLinksListsStatus($platfromUseable->id,3,$linkListMiniapp->type);
                        // 更新所有此类型链接的APPID
                        Linkslists::updateLinksAppid($appid,$platfromUseable->appid,$platfromUseable->original_id,$platfromUseable->miniapp_type);
                        // 清除数据缓存
                        DB::table("links_lists")->select("id","links_id","created_at")->where("disable",1)->where("appid",$platfromUseable->appid)->orderBy('id')->chunk(1000, function ($links_lists) {
                            foreach ($links_lists as $links_list) {
                                // 删除链接缓存数据
                                CacheService::removeLinksCache($links_list->links_id);
                            }
                        });
                        $message = "二维码小程序".$visitName."自动切换";
                        Redis::del("miniapp_change_".$platfromUseable->appid);
                        $appidNameNew = $platfromUseable->name;
                        $appidNew = $platfromUseable->appid;
                    }
                } elseif ($linkListMiniapp->type == 6) {
                    $platfromUseable = Linkslistsminapps::getPublicUseableMinapps();
                    // 免费小程序被封
                    if (empty($platfromUseable)) {
                        $message = "免费小程序".$visitName."无备用";
                    } else {
                        Redis::setex("miniapp_change_".$platfromUseable->appid,600,"1");
                        // 把小程序设为默认
                        Linkslistsminapps::updatePublicLinksListsStatus($platfromUseable->id,3,$linkListMiniapp->type);
                        $message = "免费小程序".$visitName."自动切换";
                        DB::table("links_lists")->select("id","links_id","created_at")->where("disable",1)->where("appid",$platfromUseable->appid)->orderBy('id')->chunk(1000, function ($links_lists) {
                            foreach ($links_lists as $links_list) {
                                // 删除链接缓存数据
                                CacheService::removeLinksCache($links_list->links_id);
                            }
                        });
                        Redis::del("miniapp_change_".$platfromUseable->appid);
                        $appidNameNew = $platfromUseable->name;
                        $appidNew = $platfromUseable->appid;
                    }
                }
            } else {
                // 获取独家小程序
                $usersSoleMinapp = Linkslistsminapps::getUsersSoleMinapps($linkListMiniapp->users_id);
                if (empty($usersSoleMinapp)) {
                    // 没有独家小程序了,提醒用户上架
                    $message = "小程序被".$visitName."且无备用小程序";
                } else {
                    Redis::setex("miniapp_change_".$usersSoleMinapp->appid,600,"1");
                    $message = "小程序被".$visitName."已自动切换小程序";
                    // 更新用户的APPID
                    Linkslists::updateUsersLinksAppid($users_id,$appid,$usersSoleMinapp->appid,$usersSoleMinapp->original_id,$usersSoleMinapp->miniapp_type);
                    DB::table("links_lists")->select("id","links_id","created_at")->where("disable",1)->where("appid",$usersSoleMinapp->appid)->orderBy('id')->chunk(1000, function ($links_lists) {
                        foreach ($links_lists as $links_list) {
                            // 删除链接缓存数据
                            CacheService::removeLinksCache($links_list->links_id);
                        }
                    });
                    Redis::del("miniapp_change_".$usersSoleMinapp->appid);
                }
            }

            $emailLists = [];
            if ($linkListMiniapp->status == 2) {
                $emailLists = ["714628712@qq.com","609787268@qq.com","910535996@qq.com","1406816402@qq.com"];
                $wechatOpenids = ["owYdF6vR1UVGI-YCOLA7f_DsmKlY","owYdF6lncu-z2DhgbTAMZqeXK_tY"];
                $typeLists = ["","通用小程序","公众号专用","二维码专用","客服专用","点击版专用","免费用户使用"];
                $miniappName = $linkListMiniapp->name."(共用-".$typeLists[$linkListMiniapp->type].")";
            } else {
                $userInfo = Usersinfo::getUsersInfoDetial($users_id);
                if (!empty($userInfo)) {
                    $emailLists = empty($userInfo->email) ? [] : [$userInfo->email];
                }
                $userWechat = Users::getUsersWechatOpenid($users_id);
                $wechatOpenids = [$userWechat->wechat_openid];
                $miniappName = $linkListMiniapp->name;
            }
            if (!empty($emailLists)) {
                EmailService::miniappDisableNotice($emailLists,$miniappName,$message,$appid);
            }
            foreach ($wechatOpenids as $wechatOpenid) {
                $nowTime = date("Y-m-d H:i:s",time());
                // 发送公众号消息推送
                $paramas = [
                    'first' => '',
                    'keyword1' => $miniappName,
                    'keyword2' => $message,
                    'keyword3' => $nowTime,
                    'remark' => '',
                ];
                // 开启公众号推送
                WechattmplmsgService::sendSingleTempleteMsg("q7AYyeTy8mo6SonXsMSA56pfkoy-LMioTgA1MCIJvVw",$wechatOpenid,"https://bab.moreqifu.cn/admin/miniapp/miniapp_list","","",$paramas);
            }
            // 添加小程序封禁记录
            Miniappsban::insertMiniappBanRecord($users_id,$linkListMiniapp->appid,$appidNew,$linkListMiniapp->name,$appidNameNew,$this->visit_status);
        } catch (Exception $e) {
            Log::info("Miniappdisable----------start");
            Log::info($appid);
            Log::info($e);
            Log::info("Miniappdisable----------end");
        }
    }
}
